package pl.mdziedzic.seleniumtests;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SeleniumTest2 {
	private WebDriver driver;
	private StringBuffer verificationErrors = new StringBuffer();
	private WebDriverWait wait;
	
	@Before
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		wait = new WebDriverWait(driver,10);
	}

	@Test
	public void shouldVerifyOperaDriverLicense() throws Exception {
		driver.get("http://code.google.com/p/selenium/");
		clickElement(By.linkText("Wiki"));
		insertText(By.id("searchq"), "opera");
		clickElement(By.cssSelector("span.inIssueList > form > input[type=\"submit\"]"));
		clickElement(By.linkText("OperaDriver"));
		assertTrue(isElementPresent(By.xpath("//html/body/div[3]/div/table/tbody/tr/td/div[2]/div/h1/a[2]")));
		assertEquals("OperaDriver", getText(By.xpath("//html/body/div[3]/div/table/tbody/tr/td/div[2]/div/h1/a[2]")));
		clickElement(By.linkText("available on Github"));
		driver.get("https://github.com/operasoftware/operadriver/blob/master/LICENSE.txt");
		wait.until(new ExpectedCondition<Boolean>(){
			@Override
			public Boolean apply(WebDriver driver){
				WebElement element = driver.findElement(By.xpath("//*[@class='highlight']"));
				if(element.isDisplayed()){
					return Boolean.TRUE;
				}
				return null;
			}
		});
		assertTrue(driver.findElement(By.xpath("//*[@class='highlight']")).getText().matches("^[\\s\\S]*TERMS AND CONDITIONS[\\s\\S]*$"));
	}

	@After
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}
	
	private void insertText(By id, String text) {
		WebElement element = driver.findElement(id);
		element.clear();
		element.sendKeys(text);
	}
	
	private String getText(By id){
		return driver.findElement(By.xpath("//html/body/div[3]/div/table/tbody/tr/td/div[2]/div/h1/a[2]")).getText();
	}
	
	private void clickElement(By id){
		driver.findElement(id).click();
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
}
